require 'nokogiri'
module RBPM
  module Toolkit

    # 创建活动
    def create_active
      node_name = defined?(name) ? name : id
      @process_instance.process_active_instances.create process_define_id: @process_instance.process_define_id,
                                                        bpmn_active_define_id: id, bpmn_active_name: node_name,
                                                        active_type: active_instance_type, start_date: Time.now,
                                                        status: 1, version: @process_instance.version
    end

    def sequence_flow(flow_node)
      RBPM::SequenceFlow.new(flow_node, @doc, @process_instance, last: self)
    end

    def user_task(task_node, params={})
      RBPM::UserTask.new(task_node, @doc, @process_instance, params)
    end

    def service_task(task_node, params={})
      RBPM::ServiceTask.new(task_node, @doc, @process_instance, params)
    end

    def parallel_gateway(gateway_node)
      RBPM::ParallelGateway.new(gateway_node, @doc, @process_instance)
    end

    def exclusive_gateway(gateway_node)
      RBPM::ExclusiveGateway.new(gateway_node, @doc, @process_instance)
    end

    def event(event_node)
      RBPM::Event.new(event_node, @doc, @process_instance)
    end

    # 顺序流不清楚下一步节点，需要判断
    def flow_node_initial(node, params={})
      case node.node_name
        when 'userTask' then
          user_task node, params
        when 'serviceTask' then
          service_task node, params
        when 'parallelGateway' then
          parallel_gateway node
        when 'exclusiveGateway' then
          exclusive_gateway node
        when 'endEvent' then
          event node
        else
      end
    end

    def active_instance_class
      case self.active_type
        when 0 then
          RBPM::ServiceTask
        when 1 then
          RBPM::UserTask
        when 2 then
          RBPM::ParallelGateway
        when 3 then
          RBPM::ExclusiveGateway
        else
          nil
      end
    end

    # 活动实例的种类
    def active_instance_type
      case self.class.name
        when 'RBPM::ServiceTask' then
          0
        when 'RBPM::UserTask' then
          1
        when 'RBPM::ParallelGateway' then
          2
        when 'RBPM::ExclusiveGateway' then
          3
        else
          4
      end
    end
  end
end